package com.locationtracker.plus.app.network

import android.os.Build
import com.locationtracker.plus.BuildConfig
import com.locationtracker.plus.app.util.CacheUtil
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 * 自定义头部参数拦截器，传入heads
 */
class MyHeadInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val original = chain.request()
        var builder = original.newBuilder()
        if ("GET" == original.method) {
            val urlBuilder = original.url.newBuilder()
            urlBuilder.addQueryParameter("app", "LocationTrackerPlus")
            builder.url(urlBuilder.build())
        } else {
            if (original.body is FormBody) {
                val bodyBuilder = FormBody.Builder()
                bodyBuilder.add("app", "LocationTrackerPlus")
                var formBody = original.body as FormBody
                for (i in 0 until formBody.size) {
                    bodyBuilder.add(formBody.encodedName(i), formBody.value(i))
                }
                formBody = bodyBuilder.build()
                builder = original.newBuilder().post(formBody)
            }
        }

        builder.addHeader("Accept", "application/x.dingwei.v1+json")
        builder.addHeader("VersionName", BuildConfig.VERSION_NAME)
        builder.addHeader("VersionCode", BuildConfig.VERSION_CODE.toString())
        builder.addHeader("AndroidVersion", Build.VERSION.SDK_INT.toString())
        builder.addHeader("PhoneInfo", Build.BRAND + " " + Build.MODEL)
        if (CacheUtil.isLogin()) {
            builder.addHeader("Authorization", "Bearer ${CacheUtil.getToken()}")
        }
        return chain.proceed(builder.build())
    }
}